﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace RMS.Common
{
    public class HttpHelper
    {
        /// <summary>
        /// 读取application/json提交的参数
        /// </summary>
        /// <param name="Request">提交对象</param>
        /// <returns></returns>
        public static string GetRequestPayload(HttpRequestBase Request)
        {
            Stream stream = Request.GetBufferedInputStream();
            StreamReader sr = new StreamReader(stream);
            return sr.ReadToEnd();
        }

        /// <summary>
        /// 设定参数为某个值，之后可用于转发
        /// </summary>
        /// <param name="strRequestData">RequestData的string形式</param>
        /// <param name="key">设定参数的键</param>
        /// <param name="value">设定参数的值</param>
        /// <returns></returns>
        public static string SetFormParameter(string strRequestData, string key, string value)
        {
            string para = strRequestData;
            if (para.Contains(key + "="))
            {
                var t = para.Split('&');
                for (int i = 0; i < t.Length; i++)
                {
                    if (t[i].Contains(key + "="))
                    {
                        t[i] = key + "=" + value;
                        break;
                    }
                }
                para = string.Join("&", t);
            }
            else
            {
                para += "&" + key + "=" + value;
            }
            return para;
        }
        /// <summary>
        /// 设定参数为某个值，之后可用于转发
        /// </summary>
        /// <param name="strJsonData">Json字符串数据</param>
        /// <param name="key">设定参数的键</param>
        /// <param name="value">设定参数的值</param>
        /// <returns></returns>
        public static string SetJsonParameter(string strJsonData, string key, string value)
        {
            JObject jo = JObject.Parse(strJsonData);
            if (jo[key] == null)
            {
                jo.Add(key, value);
            }
            else
            {
                jo[key] = value;
            }
            return jo.ToString();
        }
        /// <summary>
        /// Post发送请求
        /// </summary>
        /// <param name="Url">请求Url</param>
        /// <param name="postDataStr">请求参数</param>
        /// <param name="contentType">请求类型</param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr, string contentType = "application/x-www-form-urlencoded")
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = contentType;

            byte[] contentByte = System.Text.Encoding.UTF8.GetBytes(postDataStr);
            request.ContentLength = contentByte.Length;
            Stream webstream = request.GetRequestStream();
            webstream.Write(contentByte, 0, contentByte.Length);
            webstream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            if (encoding == null || encoding.Length < 1)
            {
                encoding = "UTF-8"; //默认编码
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            string retString = reader.ReadToEnd();
            return retString;
        }
        /// <summary>
        /// 以application/json形式发送请求
        /// </summary>
        /// <param name="Url">请求Url</param>
        /// <param name="postDataStr">请求参数</param>
        /// <returns></returns>
        public static string HttpPostJson(string Url, string postDataStr)
        {
            return HttpPost(Url, postDataStr, "application/json");
        }
        /// <summary>
        /// 以application/json形式发送请求
        /// </summary>
        /// <param name="Url">请求Url</param>
        /// <param name="postData">请求参数实体</param>
        /// <returns></returns>
        public static string HttpPostJson(string Url, object postData)
        {
            var postDataStr = JsonConvert.SerializeObject(postData);
            return HttpPostJson(Url, postDataStr);
        }
        /// <summary>
        /// 获取客户端真实IP
        /// </summary>
        /// <returns></returns>
        public static string GetRealIP()
        {
            string result = String.Empty;
            result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            //可能有代理   
            if (!string.IsNullOrWhiteSpace(result))
            {
                //没有"." 肯定是非IP格式  
                if (result.IndexOf(".") == -1)
                {
                    result = null;
                }
                else
                {
                    //有","，估计多个代理。取第一个不是内网的IP。  
                    if (result.IndexOf(",") != -1)
                    {
                        result = result.Replace(" ", string.Empty).Replace("\"", string.Empty);

                        string[] temparyip = result.Split(",;".ToCharArray());

                        if (temparyip != null && temparyip.Length > 0)
                        {
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                //找到不是内网的地址  
                                if (temparyip[i].IsIPAddress() && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];
                                }
                            }
                        }
                    }
                    //代理即是IP格式  
                    else if (result.IsIPAddress())
                    {
                        return result;
                    }
                    //代理中的内容非IP  
                    else
                    {
                        result = null;
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(result))
            {
                result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (string.IsNullOrWhiteSpace(result))
            {
                result = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }
        /// <summary>
        /// Post调用API返回实体结果
        /// </summary>
        /// <typeparam name="T">CommonOutPutVm.Data的类型</typeparam>
        /// <param name="Url">接口地址</param>
        /// <param name="postData">接口参数</param>
        /// <returns></returns>
        public static CommonOutPutVm GetAPIResult<T>(string Url, object postData)
        {
            var resultAPI = HttpHelper.HttpPostJson(Url, postData);
            var r = new CommonOutPutVm();
            Newtonsoft.Json.Linq.JObject resultjo = Newtonsoft.Json.Linq.JObject.Parse(resultAPI);
            r.IsSuccess = resultjo.Value<bool>("IsSuccess");
            r.Id = resultjo.Value<string>("Id");
            r.Message = resultjo.Value<string>("Message");
            if (resultjo["ErrorDic"].HasValues)
            {
                r.ErrorDic = resultjo.Value<Dictionary<string, string>>("ErrorDic");
            }
            if (r.IsSuccess && resultjo["Data"].HasValues)
            {
                r.Data = JsonConvert.DeserializeObject<T>(resultjo["Data"].ToString());
            }
            return r;
        }
    }
}
